﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Niknak.Services.TaskScheduler
{
    public static class Utils
    {
        public static T CreateInstance<T>(string forType)
        {
            Type clrType = Type.GetType(forType);

            if (clrType == null)
                throw new Exception("Invalid CLR Type " + forType);

            object instance = Activator.CreateInstance(clrType);

            if (!(instance is T))
                throw new Exception("Specified CLR Type " + forType + " does not implement " + typeof(T).ToString());

            return (T)instance;
        }

        /// <summary>
        /// See http://thevalerios.net/matt/2008/05/use-threadpoolqueueuserworkitem-with-anonymous-types/
        /// </summary>
        public static bool QueueUserWorkItem<T>(T state, Action<T> callback)
        {
            return ThreadPool.QueueUserWorkItem(s => callback((T)s), state);
        }

        public static bool QueueUserWorkItem(Action callback)
        {
            return ThreadPool.QueueUserWorkItem(s => callback());
        }
    }
}
